﻿using MediatR;
using RearLivestock.Common.Domains.Enum;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Domains.zjy;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.Echarts
{
    public class GetBreedingSowEchartsHandler : IRequestHandler<GetBreedingSowEchartsCommand, Result>
    {
        /// <summary>
        /// 基本信息仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationrepository;
        /// <summary>
        /// 种母期初仓储
        /// </summary>
        private readonly IBaseRepository<BreedingSows> breedingSowsRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<GetBreedingSowEchartsHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="basicInformationrepository"></param>
        /// <param name="breedingSowsRepository"></param>
        /// <param name="logger"></param>
        public GetBreedingSowEchartsHandler(IBaseRepository<BasicInformation> basicInformationrepository, IBaseRepository<BreedingSows> breedingSowsRepository, ILogger<GetBreedingSowEchartsHandler> logger)
        {
            this.basicInformationrepository = basicInformationrepository;
            this.breedingSowsRepository = breedingSowsRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(GetBreedingSowEchartsCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var list = (from a in (await basicInformationrepository.GetAll())
                           join b in (await breedingSowsRepository.GetAll())
                           on a.BasicInforId equals b.BasicInforId
                           group new { a, b } by new { a.Reproductivestatus } into c
                           select new PigCount()
                           {
                               name =c.Key.Reproductivestatus.ToString() ,
                               value =c.Count(),
                           }).ToList();
                result.Code = (int)CommonErrorCode.Success;
                result.Data = list;
                result.Msg = "获取种母存栏分组信息成功";
            }
            catch (Exception ex)
            {
                result.Msg = "获取种母存栏分组信息异常" + ex.Message;
                logger.LogError("获取种母存栏分组信息异常" + ex.Message);
            }
            return result;
        }
    }
}
